<?php

// 后台控制基类

namespace app\admin\base;


use app\admin\middleware\After;
use app\admin\middleware\Before;
use app\BaseController;
use app\model\Admin;
use app\model\Menu;
use app\model\Role;
use think\App;

class JwBase extends BaseController
{

    private $JwtKey = "JwCode1208";
    protected $menuAll = "php:jwcode:menuCheck";
    protected $menuUser = "php:jwcode:menuCheck:";
    // 设置中间件判断
    protected $middleware = [
        Before::class,
        After::class
    ];

    //设置参数
    public function initialize()
    {
        parent::initialize(); // TODO: Change the autogenerated stub

        //判断请求路径
        $this->controller = $this->request->controller();
        $this->action = $this->request->action();
        if ($this->controller != "Login") {
            // 获取请求头校验 jwt
            $head = $this->request->header();
            //获取全局 user_id 以及权限
            $this->cheeck($head);
            //缓存2分钟数据
            $data = Admin::cache(10)->find($this->user_id);
            if ($data->aid) {
                $this->data = $data;
            } else {
                $this->respInfo(3004);
            }

            //判断请求API,是否可以请求
            $this->menuCheck();
        }

    }

    //设置用户信息
    public function __construct(App $app)
    {
        parent::__construct($app);
    }

    /**
     * info: 校验用户信息,并保存
     * User: 伍先生
     * Argument:
     * DateTime: 2020/12/9 13:12
     * Url: cheeck
     */
    protected function cheeck($head)
    {
        if (!isset($head['authorization']) || empty($head['authorization'])) {
            $this->respInfo(3003);
        }
        $autoArr = explode(" ", $head['authorization']);

        //做个缓存
        if (cache($autoArr[1])) {
            $user = cache($autoArr[1]);
            $this->user_id = $user['aid'];
            $this->role_id = $user['role'];
        } else {
            $data = checkJwt($this->JwtKey, $autoArr[1]);
            if ($data) {
                $user = json_decode($data, 1);
                $admin = Admin::find($user['aid']);
                if ($admin->status !== 1) $this->respInfo(3002);
                $this->user_id = $admin->aid;
                $this->role_id = $admin->role;
                cache($autoArr[1], $user, 10);
            } else {
                $this->respInfo(3003);
            }
        }

    }

    /**
     * info: 设置用户认证信息
     * User: 伍先生
     * Argument:
     * DateTime: 2020/12/8 14:54
     * Url: getJwt
     */
    protected function getJwt($data)
    {
        $jwt['aid'] = $data->aid;
        $jwt['role'] = $data->role;
        $jwt['create_time'] = time(); //创建时间
        return setJwt($this->JwtKey, $jwt);
    }

    /**
     * info: 校验权限
     * User: 伍先生
     * Argument:
     * DateTime: 2020/12/9 14:07
     * Url: menuCheck
     */
    protected function menuCheck()
    {
        /*
       1 如果不在所有菜单 通过
       2 如果这条api 在用户菜单里 通过
       3 阻止就行
       */

        // 获取所有菜单 php:jwcode:menuCheck
        if (cache($this->menuAll)) {
            $menuALl = cache($this->menuAll);
        } else {
            $listStr = Menu::withAttr('site', function ($value, $data) {
                return strtolower($value);
            })
                ->where('type', 'in', "2,3")
                ->field("site")
                ->select();
            if ($listStr->isEmpty()) $this->respInfo(3000);
            $menuALl = array_column($listStr->toArray(), 'site');
            cache($this->menuAll, $menuALl, 10);
        }
        if (!in_array($this->requestUrl, $menuALl)) {
            return;
        }

        //获取用户菜单
        if (cache($this->menuUser . $this->user_id)) {
            $menuUser = cache($this->menuUser . $this->user_id);
        } else {
            $RoleStr = Role::field("role")->findOrEmpty($this->role_id);
            $data = Menu::getAutoApi($RoleStr->role);
            $menuUser = array_column($data, 'site');
            cache($this->menuUser . $this->user_id, $menuUser, 10);
        }

        if (!in_array($this->requestUrl, $menuUser)) $this->respInfo(3001);


    }

    /**
     * info: 公共返回数据
     * User: 伍先生
     * Argument:
     * DateTime: 2020/12/8 14:53
     * Url: respInfo
     */
    public function respInfo($code, $data = [], $msg = '未知')
    {
        $msg = $this->getMessage($code, $msg);
        result($data, $code, $msg);
    }

    protected function getMessage($code, $msg)
    {
        $ArrCodeMsg = [
            1000 => "成功",

            2000 => "参数错误",
            2001 => "请求方式出错",
            2002 => "系统异常",

            3000 => "失败",
            3001 => "没有权限",
            3002 => "已被拉黑",
            3003 => "权限认证失败",
            3004 => "非法登录",
        ];
        return isset($ArrCodeMsg[$code]) ? $ArrCodeMsg[$code] : $msg;
    }


}
